import Dialog from 'tdesign-miniprogram/dialog/index';
import Toast from 'tdesign-miniprogram/toast/index';
import requestApi from "../../../utils/request"


Page({
  data: {
    cartGroupData: null,
    ntotalAmount: '',
    isAllSelected: 0
  },

  // 调用自定义tabbar的init函数，使页面与tabbar激活状态保持一致
  onShow() {
    // this.getTabBar().init();
  },

  onLoad() {
    this.refreshData();
  },

  refreshData() {

    requestApi.get('shopro/cart/index', true).then(res => {
      let re = res.data
      let cartGroupData = {
        invalidGoodItems: [],
        isAllSelected: false,
        isNotEmpty: re.length > 0 ? true : false,
        selectedGoodsCount: 16,
        storeGoods: [
          {
            storeName: '默认店铺',
            promotionGoodsList: [
              {
                description: null,
                doorSillRemain: null,
                goodsPromotionList: [],
                isNeedAddOnShop: 0,
                lastJoinTime: null,
                goodsPromotionList: [],
                promotionCode: "EMPTY_PROMOTION",
                promotionId: null,
                promotionStatus: null,
                promotionSubCode: null,
                tag: null,
                tagText: null,
                title: null,
              }
            ]
          }
        ],
        totalAmount: '12121',
        totalDiscountAmount: '1212'
      }
      if (re.length > 0) {
        this.settlement(re)
        re.forEach((item) => {
          cartGroupData.storeGoods[0].promotionGoodsList[0].goodsPromotionList.push(
            {
              available: 2,
              etitle: null,
              isSelected: item.is_select,
              joinCartTime: "2020-06-29T07:55:17.000+0000",
              originPrice: undefined,
              price: item.goods.price * 100,
              primaryImage: "https://cdn-we-retail.ym.tencent.com/tsr/goods/dz-2a.png",
              putOnSale: 1,
              quantity: item.goods_num,
              roomId: null,
              saasId: "88888888",
              skuId: "135691635",
              goods_id: item.goods_id,
              sku_price_id: item.sku_price_id,
              specs: item.sku_price.goods_sku_text,
              speci_id: item.sku_price.goods_sku_id_arr,
              spuId: item.id,
              stockQuantity: item.sku_price.stock,
              stockStatus: true,
              storeId: "1000",
              tagPrice: null,
              tagText: null,
              thumb: item.goods.image,
              title: item.goods.title,
            }
          )
        })
      }
      if (cartGroupData.storeGoods.promotionGoodsList) {
        isEmpty = false
      }
      this.setData({
        cartGroupData
      });
      //预测结算商品
    })

  },
  settlement(data) {
    const goodsRequestList = []
    if (data.length == 0) { return }
    data.forEach(item => {
      if (item.is_select == 1) {
        goodsRequestList.push({
          goods_id: item.goods_id,
          goods_num: item.goods_num,
          sku_price_id: item.sku_price_id
        })
      }
    })
    if (goodsRequestList.length > 0) {
      const params = {
        goods_list: goodsRequestList,
        address_id: '1'
      };
      this.setData({ shappingList: goodsRequestList })
      requestApi.post('shopro/order/pre', params).then(res => {
        this.setData({
          ntotalAmount: res.data.total_fee * 100,
          isAllSelected: goodsRequestList.length === data.length ? 1 : 0
        });
      })
    }
  },
  findGoods(spuId, skuId) {
    let currentStore;
    let currentActivity;
    let currentGoods;
    const {
      storeGoods
    } = this.data.cartGroupData;
    for (const store of storeGoods) {
      for (const activity of store.promotionGoodsList) {
        for (const goods of activity.goodsPromotionList) {
          if (goods.spuId === spuId && goods.skuId === skuId) {
            currentStore = store;
            currentActivity = currentActivity;
            currentGoods = goods;
            return {
              currentStore,
              currentActivity,
              currentGoods,
            };
          }
        }
      }
    }
    return {
      currentStore,
      currentActivity,
      currentGoods,
    };
  },

  // 注：实际场景时应该调用接口获取购物车数据
  getCartGroupData() {
    const {
      cartGroupData
    } = this.data;
    console.log(cartGroupData)
    return Promise.resolve({
      data: cartGroupData
    });
  },

  // 选择单个商品
  // 注：实际场景时应该调用接口更改选中状态
  selectGoodsService({
    spuId,
    skuId,
    isSelected
  }) {
    this.findGoods(spuId, skuId).currentGoods.isSelected = isSelected;
    return Promise.resolve();
  },

  // 全选门店
  // 注：实际场景时应该调用接口更改选中状态
  selectStoreService({
    storeId,
    isSelected
  }) {
    const currentStore = this.data.cartGroupData.storeGoods.find((s) => s.storeId === storeId);
    currentStore.isSelected = isSelected;
    currentStore.promotionGoodsList.forEach((activity) => {
      activity.goodsPromotionList.forEach((goods) => {
        goods.isSelected = isSelected;
      });
    });
    return Promise.resolve();
  },

  // 加购数量变更
  // 注：实际场景时应该调用接口
  changeQuantityService({
    spuId,
    skuId,
    quantity
  }) {
    this.findGoods(spuId, skuId).currentGoods.quantity = quantity;
    return Promise.resolve();
  },

  // 删除加购商品
  // 注：实际场景时应该调用接口


  // 清空失效商品
  // 注：实际场景时应该调用接口
  clearInvalidGoodsService() {
    this.data.cartGroupData.invalidGoodItems = [];
    return Promise.resolve();
  },

  onGoodsSelect(e) {
    const {
      goods: {
        spuId,
        skuId
      },
      isSelected,
    } = e.detail;
    const {
      currentGoods
    } = this.findGoods(spuId, skuId);
    this.selectGoodsService({
      spuId,
      skuId,
      isSelected
    }).then(() => this.refreshData());
  },

  onStoreSelect(e) {
    const {
      store: {
        storeId
      },
      isSelected,
    } = e.detail;
    this.selectStoreService({
      storeId,
      isSelected
    }).then(() => this.refreshData());
  },

  onQuantityChange(e) {
    const {
      goods: {
        spuId,
        skuId
      },
      quantity,
    } = e.detail;
    const {
      currentGoods
    } = this.findGoods(spuId, skuId);
    const stockQuantity = currentGoods.stockQuantity > 0 ? currentGoods.stockQuantity : 0; // 避免后端返回的是-1
    // 加购数量超过库存数量
    if (quantity > stockQuantity) {
      // 加购数量等于库存数量的情况下继续加购
      if (currentGoods.quantity === stockQuantity && quantity - stockQuantity === 1) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '当前商品库存不足',
        });
        return;
      }
      Dialog.confirm({
        title: '商品库存不足',
        content: `当前商品库存不足，最大可购买数量为${stockQuantity}件`,
        confirmBtn: '修改为最大可购买数量',
        cancelBtn: '取消',
      })
        .then(() => {
          this.changeQuantityService({
            spuId,
            skuId,
            quantity: stockQuantity,
          }).then(() => this.refreshData());
        })
        .catch(() => { });
      return;
    }
    this.changeQuantityService({
      spuId,
      skuId,
      quantity
    }).then(() => this.refreshData());
  },

  goCollect() {
    /** 活动肯定有一个活动ID，用来获取活动banner，活动商品列表等 */
    const promotionID = '123';
    wx.navigateTo({
      url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
    });
  },

  goGoodsDetail(e) {
    const {
      spuId,
      storeId
    } = e.detail.goods;
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${spuId}&storeId=${storeId}`,
    });
  },

  clearInvalidGoods() {
    // 实际场景时应该调用接口清空失效商品
    this.clearInvalidGoodsService().then(() => this.refreshData());
  },

  onGoodsDelete(e) {
    const {
      goods: {
        spuId,
        skuId
      },
    } = e.detail;
    Dialog.confirm({
      content: '确认删除该商品吗?',
      confirmBtn: '确定',
      cancelBtn: '取消',
    }).then(() => {
      const params = {
        act: 'delete',
        cart_list: [spuId],
        value: 1,
        is_select: 0
      }
      requestApi.post('shopro/cart/edit', params, true).then(res => {
        this.refreshData()
      })
    });
  },

  //全选按钮
  onSelectAll(event) {
    const { isAllSelected } = event.detail
    console.log(isAllSelected)
    const params = {
      is_select: isAllSelected ? 0 : 1
    }
    requestApi.post('shopro/cart/select_all', params, true).then(res => {
      if (res.code === 1) {
        this.refreshData()
      }
    })
  },

  onToSettle() {
    const goodsRequestList = [];
    this.data.cartGroupData.storeGoods.forEach((store) => {
      store.promotionGoodsList.forEach((promotion) => {
        promotion.goodsPromotionList.forEach((m) => {
          console.log(m)
          if (m.isSelected == 1) {
            goodsRequestList.push(
              {
                goods_id: m.goods_id,
                goods_num: m.quantity,
                sku_price_id: m.sku_price_id,
              }
            );
          }
        });
      });
    });
    console.log(goodsRequestList)
    if (goodsRequestList.length > 0) {
      wx.setStorageSync('order.goodsRequestList', JSON.stringify(goodsRequestList));
      wx.navigateTo({
        url: '/service/shoppingMall/Order/order-confirm/index?type=cart'
      });
    } else {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择商品',
      });
    }
  },
  onGotoHome() {
    wx.switchTab({
      url: '/pages/shop/shop'
    });
  },
});